﻿using AutoUpdate.Log;
using ScannerApp.Common; 
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using static ScannerApp.Common.PopMessageHelper;

namespace ScannerApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class Weighing : Window
    {
       
        SerialPort sp = new SerialPort();
        private int errorlink = 0;
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        string Com = "", BaudRate = "", DataBits = "", StopRate = "", ParityRate = "";
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");
        private string strtm1 = "", strtm2 = "";
        private string lastTm = "";//最后一次有效条码
        public Weighing()
        {
            InitializeComponent();
            czy.Text = publicclass.UserName;
       

        }
  

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void ks_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ksbarcode();
                tm1.Text = "";
            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }
        private void tj_Click(object sender, RoutedEventArgs e)
        {
            tjbarcode();
            ReflashGridData();
        }

        private void tb_1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            setting window = new setting();
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();//模式，弹出！

        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
           
            MessageBoxResult result = MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                Application.Current.Shutdown();
            }
            else
            {
                
            }

        }
        /// <summary>
        /// 获取设置参数
        /// </summary>
        private void GetIni()
        {
            if (ini.ExistINIFile())
            {
                Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                BaudRate = ini.IniReadValue("串口设置", "BaudRate"); //Common.ConfigHelper.GetIni("BaudRate", "");
                DataBits = ini.IniReadValue("串口设置", "DataBits");//Common.ConfigHelper.GetIni("DataBits", "");
                StopRate = ini.IniReadValue("串口设置", "StopRate");//Common.ConfigHelper.GetIni("StopRate", "");
                ParityRate = ini.IniReadValue("串口设置", "ParityRate"); //Common.ConfigHelper.GetIni("ParityRate", "");
            }
                LinkSeriPort();
        }

        void ksbarcode()
        {
            if (tm1.Text.Trim() == "000000")//6个0，重置条码
            {
                dd.Text = "";
                zyd.Text = "";
                kh.Text = "";
                cpmc.Text = "";
                ddsl.Text = "";
                dw.Text = "";
                zd.Text = "";
                gwh.Text = "";
                cz.Text = "";
                xz.Text = "条码重置，请重新扫描"; xz.Foreground = Brushes.Red;
                //tm2.Text = "";
                tm1.Focus();
                return;
            }
            string barcode = "WK-201901090001";
            if (tm1.Text.Trim() != "") barcode = tm1.Text.Trim();
              DataTable lsdt=   sa.GetDataTable_boar_collection(barcode, "'20'");
            //var rv = SQLLogic.GetDataTable_boar_collection(barcode,"'20'");
            //if (rv.Item1)
            //{
                if (lsdt.Rows.Count > 0)
                {
                    foreach (DataRow dr in lsdt.Rows)
                    {
                        dd.Text = dr["Serialnumber"].ToString();
                        zyd.Text = barcode;
                        kh.Text = dr["cus_name"].ToString();
                        cpmc.Text=dr["product_name"].ToString();
                        ddsl.Text=dr["quantity"].ToString();
                        dw.Text = dr["unit"].ToString();
                        zd.Text=dr["DeviceName"].ToString();
                        gwh.Text=dr["BoarName"].ToString();
                        xz.Text = "使用中...";xz.Foreground = Brushes.Red;
                    // cz.Text = "210";//测试用的
                    tjbarcode();//直接就提交了
                    ReflashGridData();
                }
                tm1.Focus();
                 }
                else
                {
                    PopMessageHelper.ShowMessage("错误:此单号无效！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
                tm1.Text = ""; tm1.Focus();
             
                // MessageBox.Show("错误！此单号无效！" );
            }
            //}
            //else
            //{
            //    PopMessageHelper.ShowMessage("错误:"+ rv.Item2 + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            //  //  MessageBox.Show("错误！" + rv.Item2);
            //}
           

        }
        void tjbarcode()
        {

            //if (tm1.Text.Trim() == "000000"  )//6个0，重置条码
            //{
            //    dd.Text = "";
            //    zyd.Text = "";
            //    kh.Text = "";
            //    cpmc.Text = "";
            //    ddsl.Text = "";
            //    dw.Text = "";
            //    zd.Text = "";
            //    gwh.Text = "";
            //    cz.Text = "";
            //    xz.Text = "条码重置，请重新扫描"; xz.Foreground = Brushes.Red;
            //    //tm2.Text = "";
            //    tm1.Focus();
            //    return;
            //}
            if (cz.Text.Trim() == "" )
            {
                PopMessageHelper.ShowMessage("条码或称重不能为空！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
               // tm2.Text = ""; tm2.Focus();
                return;
            }
            //if (   strtm1 != strtm2)
            //{
            //    PopMessageHelper.ShowMessage("称重和提交的条码必须一样！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            // //   tm2.Text = ""; tm2.Focus();
            //    return;
            //}

           string msg= sa.Update_boar_collection_Weights(cz.Text, lastTm);
           // var r =  SQLLogic.Update_boar_collection_Weights(cz.Text,tm2.Text.Trim());
            if (msg=="")
            {
                PopMessageHelper.ShowMessage("提交成功！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.OK);
                string para = "{\"EventType\":\"种禽流程称重\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zyd.Text + "\",\"Log_Content\":\"" + "【重量修改】 → " + cz.Text + "\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
 
              string msglog=  sa.Sys_log(para);
                dd.Text = "";
                zyd.Text = "";
                kh.Text = "";
                cpmc.Text = "";
                ddsl.Text = "";
                dw.Text = "";
                zd.Text = "";
                gwh.Text = "";
                cz.Text = "";
                xz.Text = "闲置"; xz.Foreground = Brushes.Green;
                tm1.Focus();
            }
            else {
                PopMessageHelper.ShowMessage("提交失败！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
              //  tm2.Text = "";tm2.Focus();
                //MessageBox.Show("提交失败！"+r.Item2);
            }

           // tm2.Text = "";
        }

        private void tm1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    this._loading.Visibility = Visibility.Visible;

                    //button1.Focus();
                    lastTm = tm1.Text.Trim();
                    strtm1 = tm1.Text.Trim();
                    ksbarcode();
                    tm1.Text = "";
                    this._loading.Visibility = Visibility.Collapsed;

                }

            }
            catch (Exception ex)
            {
                PopMessageHelper.ShowMessage("错误:" + ex.Message + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }
           
        }

        private void tm2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                this._loading.Visibility = Visibility.Visible;

                if (cz.Text == "-") return;
               // strtm2 = tm2.Text.Trim();
                //button1.Focus();
                tjbarcode();
                this._loading.Visibility = Visibility.Collapsed;

            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 设置全屏
           this.WindowState = System.Windows.WindowState.Maximized;
            //this.WindowStyle = System.Windows.WindowStyle.None;
            //this.ResizeMode = System.Windows.ResizeMode.NoResize;
            //this.Topmost = true;

            //this.Left = 0.0;
            //this.Top = 0.0;
            //this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
            //this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            sysname.Text = publicclass.SystemName;
            string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");
           
            Uri uri = new Uri(preurl);
           string imageurl = uri.Scheme + "://" + uri.Host +"/"+  publicclass.SystemLogo;
            // Console.WriteLine(uri.Host);
            this.tb_1.Source = new BitmapImage(new Uri(imageurl));
            string[] s = System.IO.Ports.SerialPort.GetPortNames();
            if (ini.ExistINIFile())
            {
                string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                                                              // string Com =  Common.ConfigHelper.GetIni("Com","");
                if (s.Length < 1 || Com == "")
                {
                    zt.Text = "连接错误！";
                    errorlink = 0;
                    zt.Foreground = Brushes.Red;
                    ComSet wcs = new ComSet();
                    wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    wcs.updateMainwindowLabel += FuncSettingClosed;
                    wcs.ShowDialog();//模式，弹出！

                }
                else
                {
                    GetIni();
                }
                ReflashGridData();
            }
            else {
                zt.Text = "连接错误！请设置串口！";
            }
            //重置条码
            
            System.Drawing.Image image = BarcodeHelper.GenerateCZ("000000", 200, 50);
          
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                 // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
            cztm.Source = bi; // done!
            ms.Close();
           
            tm1.Focus();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ComSet wcs = new ComSet();
            wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen; 
            wcs.updateMainwindowLabel += FuncSettingClosed;
            wcs.ShowDialog();//模式，弹出！
        }

        //返回时候触发这个函数
        private void FuncSettingClosed(string labelContent)
        {
         string   Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                   //    string Com = Common.ConfigHelper.GetIni("Com", "");
            if (Com == "" && labelContent == "0")
            {
                PopMessageHelper.ShowMessage("检测没有初始化串口，无法采集信息，请重新设置！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

                ComSet wcs = new ComSet();
                wcs.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                wcs.updateMainwindowLabel += FuncSettingClosed;
                wcs.ShowDialog();//模式，弹出！ 

            }
            else {
                GetIni();
            }
            //label.Content = labelContent;

        }

        void LinkSeriPort()
        {

            try
            {

                //串口设置默认选择项  
                //cbSerial = 0;         
                string PortName = Com;//串口名    默认值第一个
                int BR = int.Parse(BaudRate);//获取或设置串行 波特率bit/s  默认值9600
                int DB = int.Parse(DataBits); ;//获取或设置每个字节的标准数据位长度 默认值8
                StopBits Stop = (StopBits)Convert.ToDouble(StopRate); ;//获取或设置每个字节的标准停止位数    默认值One 

                Parity ParityBits = Parity.None;//获取或设置奇偶校验检查协议    默认值None
                ParityBits = ParityRate == "None" ? Parity.None : Parity.Odd;//目前就2个
                 
                if ( sp.IsOpen)//先判断是否打开 
                  sp.Close();
                sp = new SerialPort(PortName, BR, ParityBits, DB, Stop);
                sp.WriteTimeout = 3000;
                sp.ReadTimeout = 3000;
                sp.Open();
                if (!sp.IsOpen)//再判断是否打开成功
                { 
                    errorlink++;

                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(10);
                    timer.Tick += (x, y) =>
                    {
                        zt.Text = "串口打开失败！重试(10s):" + errorlink;
                        zt.Foreground = Brushes.Red;

                        //调用函数
                        LinkSeriPort();
                    };
                    timer.Start();
                    return;
                }
                else
                {
                    zt.Text = "连接成功！";
                    errorlink = 0;
                    zt.Foreground = Brushes.Green;
                   
                    //UIAction(() =>
                    //{
                        sp.ReceivedBytesThreshold = 1;//接收缓冲区当中如果有一个字节的话就出发接收函数

                        sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //订阅委托
                    //});

                  

                   
                   
                }
            }
            catch (Exception ex)
            {
                zt.Text = "串口打开失败！！"+ ex.Message;
                zt.Foreground = Brushes.Red;
           
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！"+ ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }

        }
 


       private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            try
            {
                if (sp.IsOpen)     //此处可能没有必要判断是否打开串口，但为了严谨性，我还是加上了

                {
                    int count = sp.BytesToRead;
                    if (count <= 0 || count <= 6)//发现后面g /r/n会第二次分发
                        return;
                    Thread.Sleep(10);
                    try
                    {
                        byte[] RS232DataBuff = new byte[count];    //BytesToRead:sp1接收的字符个数 

                        try

                        {

                            Byte[] receivedData = new Byte[sp.BytesToRead];        //创建接收字节数组

                            sp.Read(receivedData, 0, receivedData.Length);         //读取数据                       

                            sp.DiscardInBuffer();                                  //清空SerialPort控件的Buffer
                            string strRcv = "";
                            string g_s_Data = "";
                            //cz.Dispatcher.BeginInvoke(new Action(() =>
                            //{
                            //  cz.Text = "0";
                            //}));
                            UIAction(() =>
                            {
                                cz.Text = "0";
                            });

                            for (int i = 0; i < receivedData.Length; i++) //窗体显示
                            {
                                //if (Convert.ToChar(receivedData[0]).ToString() == "-")
                                //{
                                //    cz.Text = "-";
                                //}
                                //if (i > 0)
                                g_s_Data += Convert.ToChar(receivedData[i]);
                                strRcv += Convert.ToChar(receivedData[i]);
                                //strRcv += receivedData[i].ToString("X2");  //16进制显示 
                            }
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]", LogType.Information, "weight");

                            string strzl = g_s_Data.Replace("g", "").Replace(" ", "").Replace("\r\n", "").Replace("+", "").Replace("\n", "").Replace("\r", "");
                            //cz.Dispatcher.BeginInvoke(new Action(() =>
                            //{
                            //    cz.Text = float.Parse(zl).ToString();
                            //}));
                            if (strzl != "")
                                UIAction(() =>
                                {
                                    cz.Text = float.Parse(strzl).ToString();
                                });
                            //SetText(zl);
                            //这里需要解析字符串
                            //正负 空格 数字（10000）.数字（1）单位（2）
                            // cz.Text = "A:"+ g_s_Data+"|B:"+strRcv;
                            // txtReceive.Text += strRcv + "\r\n";

                        }
                        catch (System.Exception ex)
                        {
                            //zt.Text = "错误:" + ex.Message;
                            //zt.Foreground = Brushes.Red;
                            Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");

                            // txtSend.Text = "";

                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.WriteLog(publicclass.UserName + "[称重]" + ex.Message, LogType.Information, "weight");

                    }

                }

                else
                {
                    //zt.Text = "串口打开失败！重试:" + errorlink;
                    //zt.Foreground = Brushes.Red;
                    LinkSeriPort();

                }
            }catch(Exception ex)
            {
                PopMessageHelper.ShowMessage("初始化错误，联系管理员！" + ex.Message + "\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);

            }


        }
        //右边处理列表
        void ReflashGridData()
        {
         DataTable lsdt=    sa.GetList_boar_collection(lastTm, "Weights");
           // var r = SQLLogic.GetList_boar_collection("");
            //if (r.Item1)
             datagrid1.ItemsSource = lsdt.DefaultView;
            //设置网格线

            datagrid1.GridLinesVisibility = DataGridGridLinesVisibility.All;
        }


       
        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }

         

        }
    }
